package commands;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import jesss.commands.JesssCommand;
import jesss.commands.JesssCommandFactoryImpl;
import jesss.options.JesssOptions;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

import static org.mockito.AdditionalMatchers.not;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.mock;

/**
 * User: Lee
 * Date: 8/22/13
 * Time: 10:29 PM
 */
public class ListObjectsCommandTests extends CommandTestsBase {


    private AmazonS3 mockS3 = mock(AmazonS3.class);
    private JesssOptions mockJesssOptions = mock(JesssOptions.class);
    private ObjectListing mockObjectListing = mock(ObjectListing.class);
    private String testBucket = "testBucket";
    private String testPrefix = "testPrefix";
    private final String delimiter = "/";

    @Before
    public void Setup() {
        stub(mockJesssOptions.getAmazonS3()).toReturn(mockS3);
        stub(mockJesssOptions.getCommandName()).toReturn("los");

        List<S3ObjectSummary> s3ObjectSummaries = makeTestS3ObjectSummaries(20, testBucket, testPrefix, delimiter);
        stub(mockObjectListing.getObjectSummaries()).toReturn(s3ObjectSummaries);
        when(mockS3.listObjects(argThat(hasValidBucket()))).thenReturn(mockObjectListing);
        stub(mockJesssOptions.getShouldDisplayVerbose()).toReturn(true);
    }

    private Matcher<ListObjectsRequest> hasValidBucket() {
        return new BaseMatcher<ListObjectsRequest>() {
            @Override
            public boolean matches(Object o) {
                return ((ListObjectsRequest)o).getBucketName().equals(testBucket);
            }

            @Override
            public void describeTo(Description description) {

            }
        };
    }

    @Test
    public void CanListObjects() throws Exception {
        String[] args = {"-bn", "testBucket", "-pre", "testPrefix", "-d", "/", "-maxKeys", "100"};

        JesssCommand listObjectsCommand = JesssCommandFactoryImpl.getInstance().createCommand(mockS3, mockJesssOptions.getCommandName(), mockJesssOptions.getShouldDisplayVerbose(), args);

        listObjectsCommand.executeCommand();
        verify(mockS3, times(1)).listObjects(any(ListObjectsRequest.class));
    }

    @Test
    public void CanListZeroObjectsIfBucketNotThere() throws Exception {
        String[] args = {"-bn", "bogus", "-maxKeys", "1000"};

        JesssCommand listObjectsCommand = JesssCommandFactoryImpl.getInstance().createCommand(mockS3, mockJesssOptions.getCommandName(), mockJesssOptions.getShouldDisplayVerbose(), args);

        listObjectsCommand.executeCommand();
        verify(mockS3, times(1)).listObjects(any(ListObjectsRequest.class));
    }
}
